var imgReady = 0, loginReady = 0, animationReady = 0;
var toast;
Page({
  data: { opacity: 1 },
  onLoad() {
    wx.setNavigationBarColor({
      animation: { 
        duration: 1500,
        timingFunc: 'linear'
      },
      frontColor: '#ffffff',
      backgroundColor: '#a1a5ff'
    });
    toast = setTimeout(() => {
      wx.showLoading({ title: '加载缓慢' })
    }, 5000)
    this.setOpacity(2000);  // invoke animation func.
   
    wx.call('getOpenid').then(login => {    // get openid with cloud func.
      wx.post('login', { openid: login.result.openid }).then(res => {
        console.log(res)
        if (!res.data || res.data == 'root') {
          wx.redirectTo({ url: '../register/register' });
          return;
        }
        wx.appData.user = res.data;
        this.updateUserInfo(res.data.id);
        switch (res.data.language) {
          case 'zh_CN': wx.lang = 0; break;
          case 'zh_TW': wx.lang = 1; break;
          case 'fr': wx.lang = 2; break;
          case 'en': wx.lang = 0; break;
        };
        // console.log('loginReady');
        this.navigate(++loginReady);
      })
    }).catch(res => {
      wx.modal('登录失败',
        '获取用户状态信息失败，请稍候再试。',
        '', 'OK'
      ).then(() => {
        this.onShow();
      })
    })
  },
  /*
   * simulate an asynchronous action
   * 模拟一个异步动作
   */
  navigate() {
    if (imgReady && loginReady && animationReady)
      wx.switchTab({ url: '../index/index' });
    clearTimeout(toast);
    wx.hideLoading();
  },
  
  /**
   * update the userInfo in database.
   * 更新用户在数据库中的信息（不是云开发里的数据库，是云数据库）
   * @param  {int} id   Use for querying
   */
  updateUserInfo(id) {
    let UU_data = {
      id: id,
      avatar: null,
      last_login: wx.formatTime(new Date(), 'date/time'),
    };
    wx.appData.user.last_login = UU_data.last_login;
    wx.getSetting({
      success:res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: info => {
              if (info.userInfo.avatarUrl != wx.appData.user.avatar) {
                UU_data.avatar = info.userInfo.avatarUrl;
                wx.appData.user.avatar = info.userInfo.avatarUrl;
              }
            },  // TODO: default image for empty avatar
            complete: () => {
              wx.post('updateUser', UU_data);
              return;
            }
          })
        } else {
          wx.post('updateUser', UU_data);
        }
      }
    })
  },


  // create an animation
  // 创建渐变动画（可计时）
  setOpacity: function (duration) {
    const fps = 60;
    if (this.data.opacity < 0) {

      setTimeout(() => {
        // console.log('animationReady')
        return this.navigate(++animationReady);
      }, 10); // 1500ms at least
    } else {
      setTimeout(() => {
        this.setData({ opacity: this.data.opacity -= fps / duration })
        this.setOpacity(duration);
      }, duration / fps);
    }
  }
})